package Concurrency.basic;

/**
 * 简单的同步容器的迭代问题
 * 简单的同步容器（即给每个容器类的方法都加上synchronized关键字）在以下三种情况可能会出现并发问题：
 * 1. 复合操作
 * 2. 伪同步
 * 3. 迭代
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SynchronizedCollectionIteration {
    private static void startModifyThread(final List<String> list) {
        Thread modifyThread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    list.add("item " + i);
                    try {
                        Thread.sleep((int) (Math.random() * 10));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        modifyThread.start();
    }

    private static void startIteratorThread(final List<String> list) {
        Thread iteratorThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    for (String str : list) {
                        System.out.println(str);
                    }
                }
            }
        });
        iteratorThread.start();
    }

    public static void main(String[] args) {
        final List<String> list = Collections.synchronizedList(new ArrayList<String>());
        startIteratorThread(list);
        startModifyThread(list);
    }
}
